package org.farm2.ai.test.client;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import lombok.extern.slf4j.Slf4j;
import org.farm2.ai.test.config.ApiConfig;
import org.farm2.ai.utils.SimpleConsoleAdvisor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import reactor.core.publisher.Flux;

@Slf4j
public class ChatDemo {
    public static void main(String[] args) {

        ChatClient client = getClient();

        sendMsg(client, "你好，我是小红");

        sendMsg(client, "我刚才说什么");
    }


    public static ChatClient getClient() {
        String apiKey = ApiConfig.apiKey;

        // 创建 DashScope API 客户端
        DashScopeApi dashScopeApi = new DashScopeApi(apiKey);
        // 构建 ChatOptions（可选参数）
        DashScopeChatOptions options = DashScopeChatOptions.builder()
                .withModel("qwen-turbo")     // 使用的模型名称
                .withTopP(0.7)
                .withTemperature(0.9)
                .build();
        // 手动创建 ChatModel 实例
        ChatModel chatModel = new DashScopeChatModel(dashScopeApi, options);


        ChatClient chatClient = ChatClient.builder(chatModel).defaultAdvisors(
                new MessageChatMemoryAdvisor(new InMemoryChatMemory())
        ).defaultAdvisors(
                new SimpleConsoleAdvisor()
        ).build();
        return chatClient;
    }

    public static void sendMsg(ChatClient chatClient, String msg) {
        Flux<String> output = chatClient.prompt()
                .user(msg)//.system("你叫小明是个10岁小朋友！")
                .stream()
                .content();


//        // ⬇️ 订阅流并打印结果
//        output.subscribe(System.out::println, error -> System.out.println(error.getMessage()), () -> {
//            System.out.println("over");
//        });
        // 等待流完成
        output.blockLast();
//        System.out.println("\n-");
//        FarmProcessUtils.sleep(2000);
    }


}